from flask import Blueprint, render_template
from flask_login import login_required
from sqlalchemy import desc
from admin.admin.admin_auth import admin_auth_bp
from admin.admin.admin_user import admin_user_bp
from admin.admin.admin_department import admin_department_bp
from admin.admin.admin_member import admin_member_bp
from admin.admin.admin_config import admin_config_bp
from admin.admin.admin_backup_route import admin_backup_bp
from admin.admin.admin_log import admin_log_bp
from inc.models import AdminUser, AdminDepartment, AdminMember, OperationLog

# 创建后台主蓝图，url_prefix 统一为 /admin
admin_bp = Blueprint('admin', __name__, url_prefix='/admin')
admin_bp.register_blueprint(admin_auth_bp)
admin_bp.register_blueprint(admin_user_bp)
admin_bp.register_blueprint(admin_department_bp)
admin_bp.register_blueprint(admin_member_bp)
admin_bp.register_blueprint(admin_config_bp)
admin_bp.register_blueprint(admin_backup_bp)
admin_bp.register_blueprint(admin_log_bp)

# 管理员仪表板首页/dashboard路由
@admin_bp.route('/')
@admin_bp.route('/index')
@login_required
def dashboard():
    """管理员仪表板，展示统计信息和最近日志/备份"""
    from inc.models import Group, BackupLog  # 局部导入，减少全局依赖
    # 获取最近的活动日志
    recent_logs = OperationLog.query.order_by(desc(OperationLog.timestamp)).limit(10).all()
    # 获取系统统计信息
    user_count = AdminUser.query.count()
    department_count = AdminDepartment.query.count()
    member_count = AdminMember.query.count()
    wx_group_count = Group.query.count()
    # 获取最近备份
    recent_backups = BackupLog.query.order_by(desc(BackupLog.backup_time)).limit(5).all()

    return render_template('admin/admin/index.html',
                           recent_logs=recent_logs,
                           user_count=user_count,
                           department_count=department_count,
                           member_count=member_count,
                           wx_group_count=wx_group_count,
                           recent_backups=recent_backups)